﻿using System;
using System.ComponentModel.Composition;
using System.Data;
using System.Linq;
using WeBlog.DataContext;
using WeBlog.Interfaces;
using WeBlog.Models;

namespace WeBlog.Repositories
{        
    public class CategoryRepository : RepositoryBase<Category>
    {       
        public CategoryRepository(IUnitOfWork unitOfWork) : base( unitOfWork )
        {            
        }

        public Category FindByName(string name)
        {
            return FindAll().SingleOrDefault(x => x.Name == name);
        }

        public Category FindById( int id )
        {
            return FindAll().SingleOrDefault(x => x.CategoryId == id);
        }

        public override void Remove(Category entity)
        {
            entity.Posts.Clear();
            base.Remove(entity);
        }        

        public IOrderedQueryable<Category> FindUsedCategories()
        {
            return FindAll().Where(x => x.Posts.Any()).OrderBy(x => x.Posts.Count);
        }
    }
}
